package com.petdog.common.exception;

import com.petdog.common.dto.ApiResponse;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import java.io.IOException;

/**
 * 全局异常处理器
 * 统一处理系统中出现的各种异常，确保API返回一致的响应格式
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理文件大小超过限制的异常
     */
    @ExceptionHandler({SizeLimitExceededException.class, FileSizeLimitExceededException.class, MaxUploadSizeExceededException.class})
    public ResponseEntity<ApiResponse<?>> handleFileSizeExceededException(Exception e) {
        logger.warn("文件大小超过限制: {}", e.getMessage());
        ApiResponse<?> response = ApiResponse.error(413, "文件大小不能超过8MB，请压缩后重新上传");
        return new ResponseEntity<>(response, HttpStatus.PAYLOAD_TOO_LARGE);
    }

    /**
     * 处理文件上传相关的IO异常
     */
    @ExceptionHandler(IOException.class)
    public ResponseEntity<ApiResponse<?>> handleIOException(IOException e) {
        logger.error("文件上传IO异常: {}", e.getMessage(), e);
        // 判断是否为网络相关错误
        if (e.getMessage().contains("Connection") || e.getMessage().contains("网络")) {
            ApiResponse<?> response = ApiResponse.error(503, "网络连接不稳定，上传失败，请检查网络后重试");
            return new ResponseEntity<>(response, HttpStatus.SERVICE_UNAVAILABLE);
        } else {
            ApiResponse<?> response = ApiResponse.error(500, "文件存储失败，请稍后再试");
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 处理文件格式不正确的异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ApiResponse<?>> handleIllegalArgumentException(IllegalArgumentException e) {
        logger.warn("参数验证失败: {}", e.getMessage());
        ApiResponse<?> response = ApiResponse.error(400, e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理缺少请求参数的异常
     */
    @ExceptionHandler(MissingServletRequestPartException.class)
    public ResponseEntity<ApiResponse<?>> handleMissingServletRequestPartException(MissingServletRequestPartException e) {
        logger.warn("缺少请求参数: {}", e.getMessage());
        ApiResponse<?> response = ApiResponse.error(400, "请选择要上传的图片文件");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<?>> handleGenericException(Exception e) {
        logger.error("未捕获的系统异常: {}", e.getMessage(), e);
        ApiResponse<?> response = ApiResponse.error(500, "服务器内部错误，请联系管理员");
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
